import {changePassword, resetPassword} from "@src/api/member";
import md5 from "@src/common/md5";
import router from "@src/router";

Component({
  data: {
    firstTips: '请设置会员余额支付密码，用于支付验证',
    secondTips: '请再次填写以确认',
    password: "",
    title: "重置支付密码",
    firstPassword: "",
    curIndex: 0,
    type: "reset",
  },
  methods: {
    onLoad(options) {
      let type = options.type
      if (!type) {
        type = "reset"
      }
      let title = "修改密码";
      if (type === "reset") {
        title = "重置支付密码"
      } else if (type === "init") {
        title = "设置支付密码"
      }
      this.setData({type: type, title: title})
    },
    confirm() {
      wx.showLoading({title: "设置中...", mask: true});
      let data = {
        oldPassword: '',
        newPassword: this.data.firstPassword //md5(this.data.firstPassword) 注释md5
      }
      let apiFun = this.data.type === 'reset' ? resetPassword : changePassword
      apiFun(data).then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          wx.showModal({
            title: '提示',
            content: '设置支付密码成功',
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                router.back();
              }
            }
          })
        }
      }).catch(() => {
        wx.hideLoading();
      })
    },
    checkPassword(value) {
      let reg = /^(\d)\1{5}$/; // 不重复6位 类似111111,222222
      let str = '0123456789_9876543210'; // str.indexOf(value) > -1 不连续判断 类似123456
      if (value.length !== 6 || reg.test(value) || str.indexOf(value) > -1) {
        wx.showToast({title: `为了你的密码安全，请不要使用6位相同或连续的数字`, icon: 'none', duration: 3000});
        return false;
      }
      return true;
    },

    processPassword() {
      let password = this.data.password;
      if (!password || password && password.length < 6) {
        return;
      }
      if (this.data.curIndex === 0) {
        if (this.checkPassword(password)) {
          this.setData({firstPassword: password, curIndex: 1, password: ""})
        } else {
          this.setData({password: "", curIndex: 0})
        }
        return;
      }
      if (this.data.firstPassword === password) {
        this.confirm();
      } else {
        wx.showToast({title: `两次输入密码不一致`, icon: 'none', duration: 3000});
        this.setData({firstPassword: "", curIndex: 0, password: ""})
      }
    },

    handlePwInput(e) {
      this.setData({password: e.detail});
      this.processPassword()
    }
  }
})
